package com.example.aloy.fragment.second

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.view.View
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.RequiresApi
import androidx.core.content.ContextCompat
import androidx.palette.graphics.Palette
import androidx.viewbinding.ViewBinding
import com.example.aloy.databinding.FragmentBannerBinding
import com.example.aloy.fragment.BasicFragment


abstract class BannerFragment : BasicFragment() {

    @ColorInt
    var textColor: Int = 0

    @ColorInt
    var textSelectedColor: Int = 0

    @ColorInt
    var backgroundColor: Int = 0

    @DrawableRes
    abstract fun getBannerDrawableRes(): Int

    override fun onBindingView(): ViewBinding {
        return FragmentBannerBinding.inflate(layoutInflater)
    }

    @RequiresApi(Build.VERSION_CODES.TIRAMISU)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        createPaletteSync(BitmapFactory.decodeResource(resources, getBannerDrawableRes()))
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        context?.let {
            (binding as FragmentBannerBinding).imageViewBanner.background =
                ContextCompat.getDrawable(it, getBannerDrawableRes())
        }
    }

    // Generate palette asynchronously and use it on a different
    // thread using onGenerated()
    private fun createPaletteSync(bitmap: Bitmap) {
        Palette.from(bitmap).generate().run {
            //设置父Fragment的主题色
            this.vibrantSwatch?.let {
                textColor = it.titleTextColor
                textSelectedColor = it.bodyTextColor
                backgroundColor = it.rgb
            }
        }
    }
}